#include "scripteditor.h"
#include "ui_scripteditor.h"
#include <QDebug>
#include <QSaveFile>
#include <QFileDialog>
#include <QDir>
#include <QFileInfo>
#include "scripthighlighter.h"
#include "process/processdialog.h"

ScriptEditor::ScriptEditor(QWidget *parent) :
  QWidget(parent),
  ui(new Ui::ScriptEditor)
{

  ui->setupUi(this);
//  setWindowFlags(Qt::SubWindow);
  setupConnections();
  new ScriptHighlighter(ui->editField->document());
//  setContextMenuPolicy(Qt::ActionsContextMenu);
  setWindowFlags(Qt::WindowStaysOnTopHint);
}

ScriptEditor::~ScriptEditor()
{
  delete ui;
}


void ScriptEditor::setupConnections()
{
  connect(ui->actionPullLines, &QAction::triggered, this, &ScriptEditor::requireLines);

  connect(ui->actionSaveScript, &QAction::triggered, this, &ScriptEditor::saveScript);

  connect(ui->actionRunIt, &QAction::triggered, this, &ScriptEditor::runProcess);

}


void ScriptEditor::acceptLines(QStringList s)
{
  QString d = ui->editField->document()->toPlainText();
  if (d.simplified().isEmpty())
    d = s.join("\n");
  else {
    d.append("\n\n");
    d.append(s.join("\n"));
  }
  ui->editField->setText(d);
  qDebug() << "Lines pulled from mainwindow.";
}

void ScriptEditor::saveScript()
{
#ifdef Q_OS_WIN
  QString filterStr = tr("批处理文件(*.bat);;所有文件(*.*)");
#else
  QString filterStr = tr("Bash脚本(*.sh);;所有文件(*.*)");
#endif

  QString outFileName = QFileDialog::getSaveFileName(this, tr("保存脚本"), QDir::homePath(), filterStr);

  QFileInfo info(outFileName);

#ifdef Q_OS_WIN
  if (info.suffix() != "bat")
    outFileName = outFileName + ".bat";
#else
  if (info.suffix() != "sh")
    outFileName = outFileName + ".sh";
#endif

  qDebug() << "output file targeted:" << outFileName;

  QSaveFile outFile(outFileName);
  if (outFile.open(QFile::WriteOnly | QFile::Truncate)) {
    QTextStream outStream(&outFile);
#ifdef Q_OS_UNIX
    outStream << "#!/bin/sh" << endl
              << "#Generated by FFFever" << endl;
#endif
    outStream << ui->editField->document()->toPlainText();
    outFile.commit();
  }
}

void ScriptEditor::runProcess()
{
  auto x = ui->editField->document()->toPlainText();
  auto xs = x.split("\n");
  QStringList filtered;
  foreach (QString l, xs) {
    l = l.simplified();
    if ((! l.isEmpty()) && (! l.startsWith("#")))
      filtered << l;
  }
  auto dialog = new ProcessDialog(filtered, this);
  dialog->show();
  dialog->startProcess();

}
